package com.fantasizegame.project.gen;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.fantasizegame.project.gen.entity.ColumnEntity;
import com.fantasizegame.project.gen.entity.TableEntity;
import com.fantasizegame.project.gen.utils.FreemarkerUtils;
import com.fantasizegame.project.gen.utils.MysqlUtils;

public class GenerateStart {

	public static void main(String[] args) throws FileNotFoundException, IOException, SQLException {

		if (args.length < 3) {
			System.out.println("请输入参数： schema，table生成路径，mapper生成路径");
			return;
		}

		File dir = new File("src/main/java");

		if (!dir.exists()) {
			dir = new File("src");
		}

		if (!dir.exists()) {
			dir = new File("");
		}

		System.out.println("生成基础路径： " + dir.getAbsolutePath());

		String				schema		= args[0];
		String				tablePath	= dir.getAbsolutePath() + "/" + args[1].replace(".", "/") + "/";
		String				mapperPath	= dir.getAbsolutePath() + "/" + args[2].replace(".", "/") + "/";

		boolean				prefix		= args.length > 3 ? Boolean.valueOf(args[3]) : false;

		List<TableEntity>	tables		= MysqlUtils.getTables(schema);

		for (TableEntity table : tables) {

			File tableFile = new File(tablePath + table.getClassName(prefix) + "Table.java");

			if (tableFile.exists()) {
				System.out.println("表 [" + table.getTableName() + "] 已存在");
				continue;
			}

			File mapperFile = new File(mapperPath + table.getClassName(prefix) + "Mapper.java");

			MysqlUtils.getColumns(schema, table);

			Map<String, Object> datas = new HashMap<>();
			datas.put("className", table.getClassName(prefix));
			datas.put("tableName", table.getTableName());

			List<Object>	cs			= new ArrayList<>();
			boolean			importArr	= false;
			for (ColumnEntity column : table.getColumns()) {

				if (column.getColumnName().equals("id") || column.getColumnName().equals("create_time") || column.getColumnName().equals("update_time")) {
					continue;
				}
				Map<String, Object> columns = new HashMap<>();
				columns.put("fieldName", column.getFieldName());
				columns.put("fieldType", column.getFieldType());
				columns.put("columnName", column.getColumnName());

				if (column.arr()) {
					importArr = true;
					columns.put("arr", 1);
				}
				columns.put("ai", column.ai() ? 1 : 0);

				cs.add(columns);

			}
			datas.put("importArr", importArr);
			datas.put("fields", cs);
			FreemarkerUtils.general("table.ftl", datas, new FileWriter(tableFile));

			Map<String, Object> mappers = new HashMap<>();
			mappers.put("className", table.getClassName(prefix));
			FreemarkerUtils.general("mapper.ftl", mappers, new FileWriter(mapperFile));

			System.out.println("表 [" + table.getTableName() + "] 已生成 [" + table.getClassName(prefix) + "]类");
		}
	}

}
